//
//  PeopleDataManager.m
//  FamilyTree
//
//  Created by student on 16/4/15.
//  Copyright © 2016年 Five. All rights reserved.
//

#import "PeopleDataManager.h"


#import "AppDelegate.h"
#import "People.h"
@interface PeopleDataManager()

@property (nonatomic,weak) AppDelegate *appDelegate;
@property (nonatomic,strong)NSMutableArray *peopleList;

@end

@implementation PeopleDataManager
SingletonM(PeopleDataManager)

//懒加载
- (NSMutableArray *)peopleList{
    if (_peopleList == nil) {
        //添加委托代码
        self.appDelegate = [UIApplication sharedApplication].delegate;
        //查询请求
        NSFetchRequest *request = [[NSFetchRequest alloc]init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"People" inManagedObjectContext:self.appDelegate.managedObjectContext];
        [request setEntity:entity];
        NSArray *results = [self.appDelegate.managedObjectContext executeFetchRequest:request error:nil];
        _peopleList = [results mutableCopy];
    }
    return _peopleList;
}

//添加人物
- (void)addPeopleInfoName:(NSString *)name
                      Sex:(NSNumber *)sex
                    Title:(NSString *)title
                DateStart:(NSDate *)dateStart
                  DateEnd:(NSDate *)dateEnd
               BirthPlace:(NSString *)birthPlace
              PeopleStory:(NSString *)story
                      Son:(NSString *)son
                 Daughter:(NSString *)daughter
                  Brother:(NSString *)broName
                   Sister:(NSString *)sisName
              PeopleImage:(NSString *)image
                 Comments:(NSString *)comments
                 PeopleID:(NSNumber *)peopleID
{
    //添加委托代码
    self.appDelegate = [UIApplication sharedApplication].delegate;
    //托管对象上下文
    People *p = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:self.appDelegate.managedObjectContext];
    //设置
    p.name = name;
    p.sex = sex;
    p.title = title;
    p.dateStart = dateStart;
    p.dateEnd = dateEnd;
    p.birthPlace = birthPlace;
    p.peopleStory = story;
    p.son = son;
    p.daughter = daughter;
    p.brother = broName;
    p.sister = sisName;
    p.peopleImage = image;
    p.comments = comments;
    p.peopleID = peopleID;
    [self.peopleList addObject:p];
    //保存
    //测试时候可以打开，其他时候在app退出后台的时候回自动保存数据库
//    [self.appDelegate.managedObjectContext insertObject:p];
//    [self.appDelegate saveContext];
}

/**
 *  查询所有人信息
 *
 *  @return 所有people对象的数组
 */
- (NSArray *)quaryAllPeopleInfo{
    return self.peopleList;
}


/**
 *  清空数据
 */

- (void)deleteAllPeopleInfo{
    for (People *p in self.peopleList) {
        [self.appDelegate.managedObjectContext deleteObject:p];
    }
    [self.peopleList removeAllObjects];
}

/**
 *  更新人物信息
 */
- (void)updatePeopleInfo{
    
}
@end
